/*
 * @Author: zhangyang
 * @Date: 2024-05-28 15:29:16
 * @LastEditTime: 2024-06-05 16:05:31
 * @Description: 
 * @LastEditors: Please set LastEditors
 * ██████╗ ██╗     ██╗   ██╗███████╗███████╗██╗   ██╗ ██████╗ ██╗   ██╗███╗   ██╗ ██████╗               ██╗    ██╗███████╗██████╗ 
 * ██╔══██╗██║     ██║   ██║██╔════╝██╔════╝╚██╗ ██╔╝██╔═══██╗██║   ██║████╗  ██║██╔════╝               ██║    ██║██╔════╝██╔══██╗
 * ██████╔╝██║     ██║   ██║█████╗  ███████╗ ╚████╔╝ ██║   ██║██║   ██║██╔██╗ ██║██║  ███╗    █████╗    ██║ █╗ ██║█████╗  ██████╔╝
 * ██╔══██╗██║     ██║   ██║██╔══╝  ╚════██║  ╚██╔╝  ██║   ██║██║   ██║██║╚██╗██║██║   ██║    ╚════╝    ██║███╗██║██╔══╝  ██╔══██╗
 * ██████╔╝███████╗╚██████╔╝███████╗███████║   ██║   ╚██████╔╝╚██████╔╝██║ ╚████║╚██████╔╝              ╚███╔███╔╝███████╗██████╔╝
 * ╚═════╝ ╚══════╝ ╚═════╝ ╚══════╝╚══════╝   ╚═╝    ╚═════╝  ╚═════╝ ╚═╝  ╚═══╝ ╚═════╝                ╚══╝╚══╝ ╚══════╝╚═════╝
 * Copyright (c) 2024 to current by BluesYoung-web, All Rights Reserved. 
 */
import 'package:flutter/material.dart';
import 'package:tdesign_flutter/tdesign_flutter.dart';
import '/database/bill.dart';
import '/database/categray.dart';
import '/routers/fluro_navigator.dart';
import '/util/toast_utils.dart';
import '/widgets/young/categray_list.dart';

class BillCreatePage extends StatefulWidget {
  const BillCreatePage({super.key});

  @override
  State<StatefulWidget> createState() => _BillCreatePageState();
}

class _BillCreatePageState extends State<BillCreatePage>
    with SingleTickerProviderStateMixin {
  late TabController tabController;
  late TextEditingController categrayController;
  late TextEditingController amountController;
  late TextEditingController remarkController;

  /// 分类
  late ICategray categray;

  /// 金额
  String amountStr = '';

  /// 备注
  String remark = '';

  /// 账单时间
  DateTime dateStr = DateTime.now();

  @override
  void initState() {
    super.initState();
    tabController = TabController(length: 2, vsync: this);
    categrayController = TextEditingController();
    amountController = TextEditingController(text: amountStr);
    remarkController = TextEditingController(text: remark);
  }

  @override
  void dispose() {
    tabController.dispose();
    categrayController.dispose();
    amountController.dispose();
    remarkController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    var args = ModalRoute.of(context)!.settings.arguments as Map;

    debugPrint('route args: ${args.toString()}');
    if (args['type'] == CategrayType.income.value) {
      debugPrint('change tab');
      tabController.index = 1;
    }

    const List<TDTab> tabs = [
      TDTab(
        text: '支出',
      ),
      TDTab(
        text: '收入',
      ),
    ];

    double formWidth = MediaQuery.of(context).size.width - 50;

    void goBack() {
      NavigatorUtils.goBackWithParams(context, {'success': true});
    }

    void addFinish() {
      showGeneralDialog(
          context: context,
          pageBuilder: (BuildContext buildContext, Animation<double> animation,
              Animation<double> secondaryAnimation) {
            return TDAlertDialog(
              title: '入账成功',
              content: '是否继续记账？',
              leftBtn: TDDialogButtonOptions(
                  title: '再记一笔',
                  titleColor: Colors.white,
                  theme: TDButtonTheme.primary,
                  action: () {
                    setState(() {
                      amountStr = '';
                      amountController.text = amountStr;

                      remark = '';
                      remarkController.text = remark;
                    });
                  }),
              rightBtn: TDDialogButtonOptions(
                  title: '返回首页',
                  titleColor: Colors.grey,
                  type: TDButtonType.ghost,
                  action: goBack),
            );
          });
    }

    Widget buildCategrayTabs() {
      return ConstrainedBox(
        constraints:
            const BoxConstraints(maxHeight: 240, maxWidth: double.infinity),
        child: TabBarView(
          controller: tabController,
          children: [
            CategrayList(
              onClickItem: (p0) {
                setState(() {
                  categray = p0;
                  categrayController.text =
                      '${p0.icon != null ? "${p0.icon} " : ""}${p0.name}';
                });
              },
            ),
            CategrayList(
              type: CategrayType.income,
              onClickItem: (p0) {
                setState(() {
                  categray = p0;
                  categrayController.text =
                      '${p0.icon != null ? "${p0.icon} " : ""}${p0.name}';
                });
              },
            )
          ],
        ),
      );
    }

    Widget buildForm() {
      return Expanded(
          child: SizedBox(
        width: double.infinity,
        child: Card(
          child: Column(
            children: [
              const SizedBox(
                height: 20,
              ),
              Container(
                padding: const EdgeInsets.only(left: 8, right: 8),
                child: Row(
                  children: [
                    Card(
                      color: Colors.white,
                      child: Container(
                          padding: const EdgeInsets.all(10),
                          child: Text(categrayController.text)),
                    ),
                    Card(
                      color: Colors.white,
                      child: Container(
                        padding: const EdgeInsets.all(10),
                        child: GestureDetector(
                          child: Row(
                            children: [
                              const Icon(
                                Icons.calendar_month,
                                color: Colors.grey,
                                size: 16,
                              ),
                              const SizedBox(
                                width: 5,
                              ),
                              Text(
                                dateStr.toLocal().toString().substring(0, 19),
                                style: const TextStyle(color: Colors.grey),
                              ),
                            ],
                          ),
                          onTap: () {
                            List<int> initDate = [
                              dateStr.year,
                              dateStr.month,
                              dateStr.day,
                            ];

                            TDPicker.showDatePicker(context,
                                title: '选择时间',
                                useHour: true,
                                useMinute: true,
                                useSecond: true,
                                dateStart: [2024, 01, 01],
                                initialDate: initDate,
                                pickerHeight: 240, onConfirm: (date) {
                              setState(() {
                                dateStr = DateTime(
                                    date['year']!,
                                    date['month']!,
                                    date['day']!,
                                    date['hour']!,
                                    date['minute']!,
                                    date['second']!);
                              });

                              // 关闭弹窗
                              Navigator.of(context).pop();
                            });
                          },
                        ),
                      ),
                    ),
                  ],
                ),
              ),
              const SizedBox(
                height: 10,
              ),
              TDInput(
                controller: amountController,
                leftLabel: '金额：',
                leftLabelStyle: const TextStyle(color: Colors.grey),
                hintText: '请输入金额',
                type: TDInputType.cardStyle,
                width: formWidth,
                inputType: TextInputType.number,
                required: true,
                onChanged: (value) {
                  setState(() {
                    amountStr = value;
                  });
                },
                onClearTap: () {
                  setState(() {
                    amountStr = '';
                    amountController.text = amountStr;
                  });
                },
              ),
              const SizedBox(
                height: 10,
              ),
              TDInput(
                controller: remarkController,
                leftLabel: '备注：',
                leftLabelStyle: const TextStyle(color: Colors.grey),
                hintText: '请输入备注',
                type: TDInputType.cardStyle,
                width: formWidth,
                onChanged: (value) {
                  setState(() {
                    remark = value;
                  });
                },
                onClearTap: () {
                  setState(() {
                    remark = '';
                    remarkController.text = remark;
                  });
                },
              ),
              const SizedBox(
                height: 20,
              ),
              TDButton(
                text: '立即入账',
                theme: TDButtonTheme.primary,
                type: TDButtonType.fill,
                width: formWidth,
                onTap: () async {
                  var amount = double.parse(amountStr);

                  if (amount <= 0) {
                    Toast.show('请输入正确的金额');
                    return;
                  }
                  if (categray.autoid == null) {
                    Toast.show('请选择分类');
                    return;
                  }

                  debugPrint('amount: $amount');
                  debugPrint('categray: ${categray.autoid}');
                  debugPrint('remark: $remark');
                  debugPrint('date: ${DateTime.now()}');

                  await DataBaseBill.createBill(IBillItem(
                      amount: amount,
                      categrayId: categray.autoid!,
                      remark: remark,
                      time: dateStr.toLocal().toString().substring(0, 19)));

                  addFinish();
                },
              )
            ],
          ),
        ),
      ));
    }

    return Scaffold(
      appBar: TDNavBar(
        useDefaultBack: false,
        leftBarItems: [
          TDNavBarItem(icon: TDIcons.close, iconSize: 24, action: goBack)
        ],
        titleWidget: TDTabBar(
          tabs: tabs,
          controller: tabController,
          showIndicator: true,
        ),
        height: 50,
      ),
      body: Container(
          padding: const EdgeInsets.all(10),
          color: Colors.white,
          child: Column(
            children: [
              buildCategrayTabs(),
              SizedBox(
                child: Container(
                  alignment: Alignment.center,
                  child: const TDDivider(
                    text: '记一笔',
                  ),
                ),
              ),
              buildForm(),
            ],
          )),
    );
  }
}
